﻿
using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 仿贴标机程序
{
    public partial class Form1 : Form
    {
        const string pLabel = @"E:\AutoLabeller20211023\PrintLabel\ReelLabel.txt";
        const string hLabel = @"E:\AutoLabeller20211023\PrintLabel\BoxLabel.txt";
        const string xLabel = @"E:\AutoLabeller20211023\PrintLabel\CaseLabel.txt";
        int scanCount = 0;
        /// <summary>
        /// 总数,来着系统
        /// </summary>
        int total = 0;
        /// <summary>
        /// 箱标数
        /// </summary>
        int xbs = 0;
        int nowTotal = 0;
        private Engine engine = null; // The BarTender Print Engine
        LabelFormatDocument btFormat;
        SQLServerDataBase sql = new SQLServerDataBase();
        public static string value;
        public Form1()
        {
            InitializeComponent();
           

        }
        public string form1name
        {
            get
            {
                return customer;
            }
            set
            {
                customer = value;
            }
        }
        private void up_Label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
       
          
        }

        private void he_Label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
         
        }

        private void boxBtw_label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
          
        }

        private void Form1_Load(object sender, EventArgs e)
        {    // 得到打印机列表
            Printers printers = new Printers();
             panPrint.Text = Properties.Settings.Default.pPrint;
            hePrint.Text = Properties.Settings.Default.hPrint;
            xiangPrint.Text = Properties.Settings.Default.xPrint;
            foreach (Printer printer in printers)
            {
                panPrint.Items.Add(printer.PrinterName);
                hePrint.Items.Add(printer.PrinterName);
                xiangPrint.Items.Add(printer.PrinterName);
            }
      
            //  cboPrinters.SelectedItem = DefaultPrinter();
            //  DefaultPrinter1 = DefaultPrinter();
            try
            {
                engine = new Engine(true);
            }
            catch (PrintEngineException exception)
            {

                MessageBox.Show(this, exception.Message);
                this.Close();
                return;
            }//加载界面，先查询有没有连接上打印机
        }
        Model md = new Model();


        /// <summary>
        /// 打印标签
        /// </summary>
        /// <param name="FieldPath">标签数据路径</param>
        /// <param name="btw_path">模板路径</param>
        /// <param name="remain">指定余数,0则自动获取标签数量</param>
        /// <param name="printName">打印机名字</param>
        void printBtw(string FieldPath, string btw_path,int remain,string printName)
        {
            try
            {
                if (remain != 0)
                {
                    md.OrderQty = remain + "";
                   
                }

                lock (engine)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
    
                string serialNumber = "LabType|xh|customer_name|customer_order_id|customer_item_name|customer_material_type|address|order_id|pn|code_type|model_type|tolerance|mattage|order_qty|remark|resistance|bc_resistance|unit|weekday|lot|quantity|qty|serial|update_time|time|status|TotolNo|TotolCnt|value1|value2|value4|value5|value6|value7|value8|value9|value10\r\n" + md.LabType  + "|" + md.Xh + "|" + md.CustomerName + "|" + md.CustomerOrderId + "|" + md.CustomerItemName + "|" + md.CustomerMaterialType + "|" + md.Address + "|" + md.OrderId + "|" + md.Pn + "|" + md.CodeType + "|" + md.ModelType + "|" + md.Tolerance + "|" + md.Mattage + "|" + md.OrderQty + "|" + md.Remark + "|" + md.Resistance + "|" + md.BcResistance + "|" + md.Unit + "|" + md.Weekday + "|" + md.Lot + "|" + md.Quantity + "|" + md.Qty + "|" + md.Serial + "|" + md.UpdateTime + "|" + md.Time + "|" + md.Status + "|" + md.TotolCnt + "|" + md.TotolCnt + "|" + md.Value1 + "|" + md.Value2 + "|" + md.Value4 + "|" + md.Value5 + "|" + md.Value6 + "|" + md.Value7 + "|" + md.Value8 + "|" + md.Value9 + "|" + md.Value10;


                using (StreamWriter stream = new StreamWriter(FieldPath))
                {
                    stream.Write(serialNumber);
                }
                //Lable 路径 

                string filePath = btw_path;
                btFormat = engine.Documents.Open(filePath);
                //如何传参 命名具名数据源 赋予对应的 key<>value
                //btFormat.SubStrings["ProductName"].Value = “test1”;
                //传入打印机名称
                btFormat.PrintSetup.PrinterName = printName;
                //打印张数
                btFormat.PrintSetup.IdenticalCopiesOfLabel =1;             
                Messages messages;
                string appName = "下标打印任务";
                Result result = btFormat.Print(appName, 10000, out messages);
          
            }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                
            }
            //btFormat.Close(SaveOptions.DoNotSaveChanges);
            //    engine.Stop();
            //}



        }

        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        StringBuilder seqArr = new StringBuilder();
        List<string> listXuhao = new List<string>();
        bool canPrint = false;
        string packing = "";
        string type = "";
        int qty = 0;
        private int printType;
        int sumTatol = 0 ;
        string codeTemp = "";
        private void button1_Click(object sender, EventArgs e)
        {//printClick
        
            string getInfo = "";
            string getStr = ErCodetextBox.Text;
            string[] arrStr = getStr.Split(',');
            packing = arrStr[0].Split(' ')[3];
            int xuhao = 0;
            qty = Convert.ToInt16(arrStr[2].Substring(2, arrStr[2].Length - 2));//来自上标签的数据
        
            try
            {
                //没抛异常就是说明匹配上了
         
            int count =  sql.ExecuteSelect_jiuwei("SELECT COUNT(*)FROM[dbo].[View_SALES_DELIVERY_JW] WHERE ITEM_CODE = '" + arrStr[0] + "' AND[销货通知单号] = '" + textBox_doc.Text + "'");
         
             
                //需要区分新老上标签

                //判断该品号是否有多条单子,同品号打5盘出一个盒标,打5个盒标出一盘箱标
                if (count>1)
            {
                if (MessageBox.Show("检测到有多个相同品号。请确认是否打印下标签?", "Confirm Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)

                {
                        //标签为是 下标签 = '是'

                    MessageBox.Show("打印下标签");
                         getInfo = "SELECT [销货通知单号],[客户名称],[客户编号],[收货地址],[序号],[品名],[订单单号],[ITEM_CODE],[单位],[数量],[库位],[上标贴],[下标贴],[围套标],[外箱标],[客户材料货号],[供应商],[客户单号],[备注],[批号],[品号],[规格],[单据日期],[客户材料规格],[客户材料品名],[图号] FROM[JW2021].[dbo].[View_SALES_DELIVERY_JW]  WHERE ITEM_CODE = '" + arrStr[0] + "' AND [销货通知单号] = '" + textBox_doc.Text + "' and [下标贴] = '是' AND 序号 NOT IN(" + seqArr + "'')" ;
                        sql.jiuwei_ExecuteNonDataSet(getInfo, out ds);

                         xuhao =  sql.ExecuteSelect_jiuwei("SELECT 序号 FROM[dbo].[View_SALES_DELIVERY_JW] WHERE ITEM_CODE = '"+ arrStr[0] + "' AND[销货通知单号] = '"+ textBox_doc.Text + "'and [下标贴] = '是' AND 序号 NOT IN(" + seqArr + "'')") ;
              
                  
                }
                else
                    {
                        getInfo = "SELECT [销货通知单号],[客户名称],[客户编号],[收货地址],[序号],[品名],[订单单号],[ITEM_CODE],[单位],[数量],[库位],[上标贴],[下标贴],[围套标],[外箱标],[客户材料货号],[供应商],[客户单号],[备注],[批号],[品号],[规格],[单据日期],[客户材料规格],[客户材料品名],[图号] FROM[JW2021].[dbo].[View_SALES_DELIVERY_JW]  WHERE ITEM_CODE = '" + arrStr[0] + "' AND [销货通知单号] = '" + textBox_doc.Text + "' and [下标贴] = '否'";
                        sql.jiuwei_ExecuteNonDataSet(getInfo, out ds);
                         xuhao = sql.ExecuteSelect_jiuwei("SELECT 序号 FROM[dbo].[View_SALES_DELIVERY_JW] WHERE ITEM_CODE = '" + arrStr[0] + "' AND[销货通知单号] = '" + textBox_doc.Text + "' and [下标贴] = '否' AND 序号 NOT IN(" + seqArr + "'') ");
      
                }
          

            }
            else//等于1
                {
                    getInfo = "SELECT [销货通知单号],[客户名称],[客户编号],[收货地址],[序号],[品名],[订单单号],[ITEM_CODE],[单位], [数量],[库位],[上标贴],[下标贴],[围套标],[外箱标],[客户材料货号],[供应商],[客户单号],[备注],[批号],[品号],[规格],[单据日期],[客户材料规格],[客户材料品名],[图号] FROM[JW2021].[dbo].[View_SALES_DELIVERY_JW]  WHERE ITEM_CODE = '" + arrStr[0] + "' AND [销货通知单号] = '" + textBox_doc.Text + "'";
                    sql.jiuwei_ExecuteNonDataSet(getInfo, out ds);
                     xuhao = sql.ExecuteSelect_jiuwei("SELECT 序号 FROM[dbo].[View_SALES_DELIVERY_JW] WHERE ITEM_CODE = '" + arrStr[0] + "' AND[销货通知单号] = '" + textBox_doc.Text + "'");
            }

                sumTatol =  sql.ExecuteSelect_jiuwei("SELECT SUM(数量) FROM[dbo].[View_SALES_DELIVERY_JW] WHERE ITEM_CODE = '" + arrStr[0] + "' AND[销货通知单号] = '" + textBox_doc.Text + "'");
                this.dataGridView1.Rows[xuhao - 1].Selected = true;
                this.dataGridView1["已扫数量", xuhao - 1].Value = havQty;
                dataGridView1.CurrentCell = dataGridView1.Rows[xuhao - 1].Cells[1];


                dt = ds.Tables[0];
                total = Convert.ToInt32(dt.Rows[0]["数量"]);
                if (scanCount == 0)//第一次扫描时，记录
                {
                    codeTemp = dt.Rows[0]["品名"].ToString();
                    nowTotal = sumTatol;//第一次记录

                }

          
                if (codeTemp!=  dt.Rows[0]["品名"].ToString())
                {
                    scanCount = 0;
                    havQty = 0;
                  
                }
           // md.LabType = 
                md.Xh = dt.Rows[0]["序号"].ToString();
                md.OrderId = dt.Rows[0]["订单单号"].ToString();
                md.CustomerOrderId = dt.Rows[0]["客户单号"].ToString();
                md.CustomerName = dt.Rows[0]["客户名称"].ToString();
                md.CustomerMaterialType = dt.Rows[0]["客户材料规格"].ToString();
                md.Lot = arrStr[3].ToString().Substring(2, 10);
                md.ModelType = dt.Rows[0]["规格"].ToString();
                md.OrderId = dt.Rows[0]["客户名称"].ToString();
                md.Quantity = qty+"";
                md.Value1 = dt.Rows[0]["客户材料货号"].ToString();
                md.Address = dt.Rows[0]["收货地址"].ToString();
                md.Pn = dt.Rows[0]["ITEM_CODE"].ToString();
                md.CustomerItemName = dt.Rows[0]["品名"].ToString();
                md.Qty = qty + "";
                md.Unit = dt.Rows[0]["单位"].ToString();
                md.Resistance = arrStr[0].Split(' ')[2];
                md.CodeType = arrStr[0].Split(' ')[0];
                md.Weekday = arrStr[3].ToString().Substring(2,4);
                
            }
            catch (Exception ex)
            {
                
                MessageBox.Show("扫描的品号不存在"+ex.Message);
                return;
            }
            int a = total;
            if (havQty >= a)
            {//当前品号打完,需要选择下一个品号
                MessageBox.Show("请更换其他品号");
                havQty = 0;
                bool isRepeat = listXuhao.Select(i => i.ToString()).Distinct().Count() != listXuhao.Count;
                if (!isRepeat)
                {
                    listXuhao.Add(xuhao.ToString());
                }
                if (listXuhao.Count > 0)
                {
                    foreach (var item in listXuhao)
                    {
                        seqArr.AppendFormat(item + ",");
                    }

                }
                return;
            }


           
            printBtw(pLabel, up_Label.Text,0,panPrint.Text);//盘标
            scanCount++;//盘标打印数   除了2010,2512 是7盘打一盒,其他都是10盘打一盒
            nowTotal -= qty / 1000;//每扫一次，就从总数中扣除
            if (nowTotal!=0)
            {//打完10盘后，出一次盒标
                hbs++;


                if (hbs!=0&&hbs % 6 == 0)
                {
                    print_xb();//箱标
                    xbs++;
                }
                //  scanCount = 0;

                switch (md.ModelType)
                {
                    case "0201":
                    case "0402":
                    case "0603":
                    case "0805":
                    case "1210":
                        if (scanCount % 10 == 0)//打盒标
                        {
                            printType = 0;//打整
                            print_hb();//盒标

                            hbs++;
                        }
                        else
                        {
                            normalPrint();
                        }
                        break;
                    case "2010":
                    case "2512":
                        if (scanCount % 7 == 0)//打盒标
                        {
                            printType = 0;//打整
                            print_hb();
                            hbs++;
                        }
                        else
                        {
                            normalPrint();
                        }
                        break;
                }

            }
            else
            {
                normalPrint();
            }
         
            havQty += qty / 1000;
            this.dataGridView1["已扫数量", xuhao - 1].Value = havQty;
         
        }

       void normalPrint()
        {
            //直接查询一下剩余数量是不是等于应该等于的余数
            //   canPrint = true;
            int box_count;

            int moreBoxNum = getMore(total, out box_count)[1]; //余数
                                                               // int ys = Convert.ToInt32(Convert.ToDouble(total_num) % 50);//y余数
            if (nowTotal == 0)//剩余数量=0时，说明此盘是最后一批料
            {
                print_hb();//打盒标余数
                Thread.Sleep(1000);

                MessageBox.Show("开始打印箱数");



                print_xb();//打箱标余数

            }
         
        }

        private int[] getMore(int total,out int box_count)//箱标
        {
            int[] arrNum = new int[2];
            box_count = 0;
            int boxNum = 0;
            string[] contentArr = new string[20];
            string[] ItemCode_arr = new string[20];
         //   int box_count = 0;
           
       //2010/2512 7卷   other  10卷

            switch (md.ModelType)
            {
                case "0201":
                    if (packing == "P10")
                    {//求余
                        box_count = 600;
                        boxNum = total % box_count;//箱标余数
                        heNum = total % (10 * qty / 1000);//盒标余数
                    }
                    else {
                        box_count = 900;
                        boxNum = total % box_count;
                        heNum = total % (10 * qty / 1000);
                    }    
                    
                    break;
                case "0402":
                    box_count = 600;
                    boxNum = total % box_count;
                    heNum = total % (10 * qty / 1000);
                    break;
                case "0603":
                    box_count = 300;
                    boxNum = total % box_count;
                    heNum = total % (10 * qty / 1000);
                    break;
                case "0805": 
                    box_count = 300;
                    heNum = total % (10 * qty / 1000);
                    boxNum = total % box_count;
                    break;
                case "1206":
                    box_count = 300;
                    boxNum = total % box_count;
                    heNum = total % (10 * qty / 1000);
                    break;
                case "1210":
                    box_count = 300;
                    boxNum = total % box_count;
                    heNum = total % (10 * qty / 1000);
                    break;
                case "2010":
                    box_count = 168;
                    boxNum = total % box_count;
                    heNum = total % (7 * qty / 1000);
                    break;
                case "2512":
                    box_count = 168;
                    boxNum = total % box_count;
                    heNum = total % (7 * qty / 1000);
                    break;
            }
            arrNum[0] = heNum;
            arrNum[1] = boxNum;
            return arrNum;
        
        }
        private void print_hb()
        {
            //RC 0402 F N 0R11 P 5000 2323C00789 盒标
            //盒标，假设每盒500k,总量1020，打3盒，2盒500，1盒20
            //if (!canPrint)
            //{
            //    MessageBox.Show("不满足扫描5次，不得打印");
            //    return;
            //}
            try
            {
          
                int box_count;
              
                int boxNum = getMore(total, out box_count)[0];//获取打印余数



                if (boxNum > 0)
                {//有余数，多打一盒，数量为余数
                 //  150 < 50
                    printBtw(pLabel, he_Label.Text, boxNum, hePrint.Text);
                }
                else
                {//整数就打整数
                    printBtw(pLabel, he_Label.Text, boxNum, hePrint.Text);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("输入的盘标格式不正确");
            }

        }
        private void print_xb()
        {
            //RC 0402 F N 0R11 P 5000 2323C00789 箱标
            //箱标的数量标准是，根据订单总数进行拆解，0402每箱是1250K，0603 / 0805 / 1206每箱是500K

         
            try
            {
             
               // PrinterFlag = 3;
       
                int box_count = 0;
             
                int moreBoxNum = getMore(total, out box_count)[0]; //余数

             
             printBtw(xLabel, boxBtw_label.Text, moreBoxNum, xiangPrint.Text);               
            
                
            }
            catch (Exception error)
            {

                MessageBox.Show(error.Message);
                return;
            }

        }
 
        string customer = "";
        private int havQty=0;
        private int hbs=0;
        /// <summary>
        /// 盒数
        /// </summary>
        private int heNum;

        private void button2_Click(object sender, EventArgs e)
        {
            scanCount = 0;
            hbs = 0;
            xbs = 0;
            DataSet ds = new DataSet();
            DataSet ds1 = new DataSet();
           string sqlStr = "SELECT [序号], [销货通知单号],[客户名称],[客户编号],[收货地址],[品名],[订单单号],[ITEM_CODE],[单位],[数量], '"+ 0 +"' as 已扫数量,[库位],[上标贴],[下标贴],[围套标],[外箱标],[客户材料货号],[供应商],[客户单号],[备注],[批号],[品号],[规格],[单据日期],[客户材料规格],[客户材料品名],[图号] FROM[JW2021].[dbo].[View_SALES_DELIVERY_JW] WHERE [销货通知单号] = '" + textBox_doc.Text + "'";

            try
            {
                sql.jiuwei_ExecuteNonDataSet(sqlStr, out ds);
                dataGridView1.DataSource = ds.Tables[0];
               // ds.Tables[0].Rows[0][2].ToString()
                customer = ds.Tables[0].Rows[0][2].ToString();
                label_cusmter.Text = customer;
                value = customer;
                string select_jw_bartender = "SELECT * FROM [dbo].[jw_bartender] WHERE custom_name = '" + customer + "'";
                sql.ExecuteNonDataSet(select_jw_bartender, out ds1);
                up_Label.Text = ds1.Tables[0].Rows[0][1].ToString();
                he_Label.Text = ds1.Tables[0].Rows[0][2].ToString();
                boxBtw_label.Text = ds1.Tables[0].Rows[0][3].ToString();
            
            }
            catch (Exception)
            {
                up_Label.Text = "null";
                he_Label.Text = "null";
                boxBtw_label.Text = "null";
                MessageBox.Show("可能的原因：1、输入单号不正确2、客户模板不存在");
                return;
            }


        

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (label_cusmter.Text== "C00000")
            {
                MessageBox.Show("请先查询销货单号"); return;
            }

            new loginFrom().ShowDialog();
        }
        static void KillBarTender()
        {
            try
            {
                foreach (var process in Process.GetProcessesByName("bartend"))
                {
                    process.Kill();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error killing BarTender: {ex.Message}");
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            KillBarTender();

        }

        private void panPrint_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void panPrint_SelectedIndexChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.pPrint = panPrint.SelectedItem.ToString();

            // 保存修改（仅用户级配置需要）
            Properties.Settings.Default.Save();
        }

        private void hePrint_SelectedIndexChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.hPrint = hePrint.SelectedItem.ToString();

            // 保存修改（仅用户级配置需要）
            Properties.Settings.Default.Save();
        }

        private void xiangPrint_SelectedIndexChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.xPrint = xiangPrint.SelectedItem.ToString();

            // 保存修改（仅用户级配置需要）
            Properties.Settings.Default.Save();
        }
    }
}
